package com.exam.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.exam.pojo.domain.Question;
import com.exam.pojo.domain.QuestionCategory;
import com.exam.pojo.domain.User;
import com.exam.pojo.vo.QuestionCategoryVO;
import com.exam.service.IQuestionCategoryService;
import com.exam.utils.CollUtils;
import com.exam.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class QuestionCategoryServiceImpl implements IQuestionCategoryService {

    private final MongoTemplate mongoTemplate;

    @Override
    public List<QuestionCategoryVO> list(String uuid) {
        List<QuestionCategory> list = mongoTemplate.findAll(QuestionCategory.class);
        if(StringUtils.isNotEmpty(uuid)){
            Map<String, QuestionCategory> map = CollUtils.fieldValueMap(list, "id");
            //获取用户做过的题目
            User user = mongoTemplate.findById(uuid, User.class);
            if(user!=null){
                List<Long> finishQuestionIds = user.getFinishQuestionIds();
                Criteria criteria = new Criteria();
                if(CollUtils.isNotEmpty(finishQuestionIds)){
                    criteria.and("id").nin(finishQuestionIds);
                }
                AggregationResults<QuestionCategoryVO> result = mongoTemplate.aggregate(Aggregation.newAggregation(
                        Aggregation.match(criteria),
                        Aggregation.group("cateId").count().as("counts")
                ), Question.class, QuestionCategoryVO.class);
                List<QuestionCategoryVO> voList = result.getMappedResults();
                for (QuestionCategoryVO vo : voList) {
                    BeanUtil.copyProperties(map.get(vo.getId()),vo);
                }
                return voList;
            }
        }
        return BeanUtil.copyToList(list,QuestionCategoryVO.class);
    }
}
